﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using Microsoft.SharePoint;

namespace SlamCms.SharePoint.Tagging
{
	internal class TagTreeNode : TreeNode
	{
		private StateBag _viewState;

		public bool Enabled
		{
			get
			{
				bool enabled = true;
				if (ViewState["Enabled"] != null)
				{
					enabled = (bool)ViewState["Enabled"];
				}
				return enabled;
			}
			set
			{
				ViewState["Enabled"] = value;
			}
		}

		private StateBag ViewState
		{
			get
			{
				if (_viewState == null)
				{
					_viewState = new StateBag();
					if (IsTrackingViewState)
					{
						((IStateManager)_viewState).TrackViewState();
					}
				}
				return _viewState;
			}
		}

		public TagTreeNode() :
			base()
		{
		}

		public TagTreeNode(string text) : 
			base(text)
		{
		}

		public TagTreeNode(string text, string value) : 
			base(text, value)
		{
		}

		public TagTreeNode(string text, string value, string imageUrl) : 
			base(text, value, imageUrl)
		{
		}

		public TagTreeNode(string text, string value, string imageUrl, string navigateUrl, string target)
			: base(text, value, imageUrl, navigateUrl, target)
		{
		}

		protected override void RenderPostText(System.Web.UI.HtmlTextWriter writer)
		{
			writer.AddAttribute(HtmlTextWriterAttribute.Type, "hidden");
			writer.AddAttribute(HtmlTextWriterAttribute.Value, Value.ToString() + "," + Enabled.ToString());
			writer.RenderBeginTag(HtmlTextWriterTag.Input);
			writer.RenderEndTag();

			base.RenderPostText(writer);
		}

		protected override object SaveViewState()
		{
			object[] baseViewState = (object[])base.SaveViewState();
			object[] viewStateObjects = new object[3];
			if (baseViewState != null)
			{
				viewStateObjects[0] = baseViewState[0];
				viewStateObjects[1] = baseViewState[1];
			}
			if (this.ViewState != null)
			{
				viewStateObjects[2] = ((IStateManager)ViewState).SaveViewState();
			}
			if ((baseViewState == null) && (viewStateObjects[2] == null))
			{
				return null;
			}
			return viewStateObjects;
		}

		protected override void LoadViewState(object state)
		{
			base.LoadViewState(state);

			object[] viewStateObjects = (object[])state;
			if (viewStateObjects != null)
			{
				if (viewStateObjects[2] != null)
				{
					((IStateManager)this.ViewState).LoadViewState(viewStateObjects[2]);
				}
			}
		}
	}
}
